package com.yb.login.center.strategy.user;

import com.yb.auth.core.bean.SysUser;
import com.yb.auth.core.bean.SysUserMobileAuthentication;
import com.yb.auth.core.constant.LoginConstant;
import com.yb.auth.core.util.SecurityUtils;
import com.yb.core.constant.HttpConstant;
import com.yb.core.constant.RedisConstant;
import com.yb.core.exception.YbBusinessException;
import com.yb.core.util.JwtTokenUtil;
import com.yb.core.util.RedisUtil;
import com.yb.login.center.template.AbstractUserServiceTemplate;
import com.yb.login.center.vo.LoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Objects;

/**
 * Copyright (C), 2022-2022, 姚兵
 * Author: 32210
 * Date: 2022/11/12 22:23
 * FileName: LoginServiceImpl
 * Description:
 */

@Service
@Slf4j
public class UserMobileLoginStrategy extends AbstractUserServiceTemplate {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public Authentication loadAuthentication(LoginVo loginVo) {
        String mobile = loginVo.getMobile();

        if(Objects.isNull(mobile)){
            throw new YbBusinessException(HttpConstant.Response.MOBILE_ERROR);
        }

        String verifyCode = loginVo.getVerifyCode();
        if(!StringUtils.hasText(verifyCode)){
            throw new YbBusinessException(HttpConstant.Response.VERIFY_CODE_EMPTY);
        }


        Authentication authenticationToken = new SysUserMobileAuthentication(mobile,verifyCode);

        return authenticationToken;
    }

    @Override
    public SysUser loadSysUser(Authentication authentication) {
        if(authentication instanceof SysUserMobileAuthentication){
            SysUserMobileAuthentication sysUserPassAuthentication = (SysUserMobileAuthentication) authentication;
            return sysUserPassAuthentication.getSysUser();
        }
        return null;
    }

    @Override
    protected LoginConstant.LoginType getLoginType() {
        return LoginConstant.LoginType.USER_MOBILE;
    }

    @Override
    protected void onSuccess() {
        Authentication authentication = SecurityUtils.getAuthentication();
        log.info("onSuccess:{}",authentication);
        if(authentication instanceof SysUserMobileAuthentication){
            SysUserMobileAuthentication sysUserMobileAuthentication= (SysUserMobileAuthentication) authentication;
            String mobile = sysUserMobileAuthentication.getMobile();
            log.info("onSuccess:{}",mobile);
            redisUtil.delete(String.format(RedisConstant.MOBILE_VERIFY_CODE,mobile));
        }
    }
}
